package com.danco.training.zaneuskaya.faces.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import com.danco.training.zaneuskaya.domain.City;
import com.danco.training.zaneuskaya.service.CityService;
import com.danco.training.zaneuskaya.service.impl.CityServiceImpl;


@FacesConverter(forClass = City.class)
public class CityConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		CityService service = new CityServiceImpl();
		Integer cityId;

		try {
			cityId = Integer.parseInt(arg2);
		} catch (NumberFormatException exception) {
			throw new ConverterException(new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "", ""));
		}

		return service.getEntityById(cityId);
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {

		if (arg2 == null) {
			return "";
		}
		City city = (City) arg2;
		return String.valueOf(city.getCityId());
	}
}
